clear

use "$BS_fold/local1/decomposition_SS_ProdR_new_kl", clear

xtset  co_code1 year, yearly
destring(nic_08_2dig), g(nic2)

gen diff_ln_IND = ln_IND - L.ln_IND
gen diff_ln_IVS = ln_IVS - L.ln_IVS
gen diff_tfpr = tfpr - L.tfpr

foreach var in wIPT_IND_CHN wIPT_LMI_CHN_EXCL_IND rwIPT_IND_CHN rwIPT_LMI_CHN_EXCL_IND {
	generate ln_`var' = ln(`var')
	generate diff_`var' = ln_`var' - L.ln_`var'
}

foreach v in diff_tfpr diff_ln_IND diff_ln_IVS {
	drop if missing(`v')
}

** To get the final sample for all regs:
	ivreghdfe drop_term (diff_ln_IND  diff_wIPT_IND_CHN = diff_ln_IVS diff_wIPT_LMI_CHN_EXCL_IND ), a(nic2#year) first cluster(nic_08_4dig)
			generate sample0 = e(sample)
			keep if sample0 == 1
			

egen nic2_year = group(nic_08_2dig year)

preserve
	clear
	set obs 1
	generate variable = ""
	generate Across = .
	generate Within = .
	save "$working/variance_decomp", replace

restore

foreach v in diff_ln_IND diff_ln_IVS diff_wIPT_IND_CHN diff_wIPT_LMI_CHN_EXCL_IND {

	preserve
		bysort nic2_year: egen m_`v' = mean(`v')
		generate dm_`v' = `v' - m_`v'
		drop if m_`v' == .
		drop if dm_`v'==.
		
		sum `v', detail
		local CV = r(Var)
		sum m_`v', detail
		local m_CV = r(Var)
		sum dm_`v', detail
		local dm_CV = r(Var)
		
		clear
		
		set obs 1
		generate variable = "`v'"
		generate Across = `m_CV'/`CV'
		generate Within = `dm_CV'/`CV'
		
		tempfile t1
		save `t1', replace
		
		clear
		use "$working/variance_decomp"
		append using `t1'
		save "$working/variance_decomp", replace
	restore
	
}

clear

use "$working/variance_decomp"

drop if Across==.

replace variable = "OutputComp" if variable=="diff_ln_IND"
replace variable = "InputAccess" if variable=="diff_wIPT_IND_CHN"
replace variable = "OutputCompIV" if variable=="diff_ln_IVS"
replace variable = "InputAccessIV" if variable=="diff_wIPT_LMI_CHN_EXCL_IND"

replace Across = Across*100
replace Across = round(Across, 0.01) 

replace Within = Within*100
replace Within = round(Within, 0.01) 

	texsave variable Across Within using "$tables/VarianceDecomp.tex", ///
		title("Variance Decomposition of Import Variables") ///
		nofix replace location(h) marker(tab:VarDecomp) frag ///
		autonumber width(1.1\textwidth)
